<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2006/10/09 20:05:25 $)
// $RCSfile: functions_alertrules.php,v $ : $Revision: 1.26 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Alert Rules Class
*/
class TicketAlertRules
{
	var $ticketobj;
	var $departmentid;
	var $loaded = false;
	var $alertscache = array();
	var $infolist = array();
	var $templatecache = array();
	var $alert = array();
	var $cached = false;
	var $attachments = array();

	/**
	* Constructor
	*/
	function TicketAlertRules(&$ticketobj)
	{
		global $_SWIFT, $template;

		$this->ticketobj = &$ticketobj;
		$this->departmentid = $ticketobj->ticket["departmentid"];
		$this->ticket = &$ticketobj->ticket;

		if (!empty($this->departmentid))
		{
			$this->loaded = true;

			// Make sure we process the rules on shutdown
			register_shutdown_function(array(&$this, 'processRules'));
		}

		$template->loadLanguageSection("staff_talertrules", TEMPLATE_FILE);
	}

	/**
	* Add attachments for alert rules
	*/
	function addAttachments($attachments)
	{
		$this->attachments = $attachments;
	}

	/**
	* Processes all the given rules for a ticket on shutdown
	*/
	function processRules()
	{
		global $dbCore, $_SWIFT, $template;

		if (defined("SWIFTCUSTOMPATH"))
		{
			chdir(SWIFTCUSTOMPATH);
		} else {
			chdir(dirname(__FILE__)."/../../.");
		}

		$this->ticketobj->processTicketQueries();

		if (!_is_array($this->alertscache))
		{
			return false;
		}

//		echo "Doing Rule Process..<BR />";

		// Get all the rules for the given action under this department
		$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."alertactions` AS alertactions LEFT JOIN `". TABLE_PREFIX ."alertrules` AS alertrules ON (alertactions.alertruleid = alertrules.alertruleid) WHERE alertactions.actiontype IN (". buildIN($this->alertscache) .");");
		while ($dbCore->nextRecord())
		{
			$_ticket = $this->ticketobj->ticket;
			if (($dbCore->Record["departmentid"] == 0 || $dbCore->Record["departmentid"] == $_ticket["departmentid"]) && ($dbCore->Record["ticketstatusid"] == 0 || $dbCore->Record["ticketstatusid"] == $_ticket["ticketstatusid"]) && ($dbCore->Record["priorityid"] == 0 || $dbCore->Record["priorityid"] == $_ticket["priorityid"]))
			{
				$this->alert = $dbCore->Record;

				$template->assign("alert", $dbCore->Record);
				$template->assign("alerttype", iif($dbCore->Record["alerttype"]==ALERT_SMS, "sms", "email"));
				$template->assign("alertdata", $this->infolist[$dbCore->Record["actiontype"]]);
				switch ($dbCore->Record["actiontype"])
				{
					case ALERT_NEWTICKET:
//						echo "New Ticket Alert Triggered<BR />";
						$this->doNewTicketAlert($dbCore->Record, $this->infolist[ALERT_NEWTICKET]);
						break;
					case ALERT_NEWREPLY:
						$this->doNewReplyAlert($dbCore->Record, $this->infolist[ALERT_NEWREPLY]);
						break;
					case ALERT_NEWSTAFFREPLY:
						$this->doNewReplyAlert($dbCore->Record, $this->infolist[ALERT_NEWSTAFFREPLY], true);
						break;
					case ALERT_MOVE:
						$this->doTicketMoveAlert($dbCore->Record, $this->infolist[ALERT_MOVE]);
						break;
					case ALERT_FLAG:
						$this->doTicketFlagAlert($dbCore->Record, $this->infolist[ALERT_FLAG]);
						break;
					case ALERT_NOTE:
						$this->doTicketNoteAlert($dbCore->Record, $this->infolist[ALERT_NOTE]);
						break;
					case ALERT_STATUS:
						$this->doStatusChangeAlert($dbCore->Record, $this->infolist[ALERT_STATUS]);
						break;
					case ALERT_EDIT:
						$this->doTicketEditAlert($dbCore->Record, $this->infolist[ALERT_EDIT]);
						break;
					case ALERT_PRIORITY:
						$this->doPriorityChangeAlert($dbCore->Record, $this->infolist[ALERT_PRIORITY]);
						break;
					case ALERT_ASSIGN:
						$this->doTicketAssignAlert($dbCore->Record, $this->infolist[ALERT_ASSIGN]);
						break;
					case ALERT_MERGE:
						$this->doTicketMergeAlert($dbCore->Record, $this->infolist[ALERT_MERGE]);
						break;
					case ALERT_DELETEPOST:
						$this->doPostDeleteAlert($dbCore->Record, $this->infolist[ALERT_DELETEPOST]);
						break;
					case ALERT_DELETETICKET:
						$this->doTicketDeleteAlert($dbCore->Record, $this->infolist[ALERT_DELETETICKET]);
						break;
				}
			}
		}
		unset($this->alertscache);
	}

	/**
	* Raises a given rule and adds it to the cache
	*/
	function raiseAlert($alertaction, $info = "")
	{
		global $dbCore, $_SWIFT, $template;

		if ($this->ticketobj->noalertrules == true)
		{
			return false;
		}

		$this->alertscache[] = $alertaction;
		$this->infolist[$alertaction] = $info;

//			$template->cache(array('alert_flag', 'alert_newticket', 'alert_newreply', 'alert_addnote', 'alert_ticketmove', 'alert_ticketstatus', 'alert_ticketpriority', 'alert_ticketassign', 'alert_ticketposdelete'));

		if (defined("ISMODERNBILL"))
		{
			$this->processRules();
		}

		return true;
	}

	/**
	* Gets the Staff List who are assigned to the departmentid for the current ticket
	*/
	function getStaffList($departmentid = false)
	{
		global $_SWIFT;

//		echo "Calling Get Staff List<BR />";

		$staffidlist = $staffgroupidlist = $stafflist = $prstaffidlist = array();

		if (!$departmentid)
		{
			$departmentid = $this->ticket["departmentid"];
		}

		if (_is_array($_SWIFT["groupassigncache"]))
		{
			foreach ($_SWIFT["groupassigncache"] as $key=>$val)
			{
				$staffgroupid = $key;
				$departmentidlist = &$val;

				if (in_array($departmentid, $departmentidlist))
				{
					$staffgroupidlist[] = $staffgroupid;
				}
			}
		}

		if (_is_array($_SWIFT["staffassigncache"]))
		{
			foreach ($_SWIFT["staffassigncache"] as $key=>$val)
			{
				$staffid = $key;
				$departmentidlist = &$val;

				if (in_array($departmentid, $departmentidlist))
				{
					$staffidlist[] = $staffid;
				}
			}
		}

		// Now that we have a list of staff and staff groups, we make the final staff list
		foreach ($_SWIFT["staffcache"] as $key=>$val)
		{
			if (((in_array($val["staffid"], $staffidlist) || (in_array($val["staffgroupid"], $staffgroupidlist) && $val["groupassigns"] == 1)) && ($this->alert["alertscope"] == "1" || ($this->alert["alertscope"] == "0" && $this->alert["staffid"] == $val["staffid"]))) && !in_array($val["staffid"], $prstaffidlist))
			{
				$stafflist[] = $val;
				$prstaffidlist[] = $val["staffid"];
//				print_r($prstaffidlist);
//				echo "Alert Scope: ".$this->alert["alertscope"]."<BR />Alert Staff ID: ".$this->alert["staffid"]."<BR />Staff ID: ".$val["staffid"]."<HR />";
			}
		}

		return $stafflist;
	}

	/**
	* Processes the Alert, Parses the template and takes the relevant action
	*/
	function processAlert($templatename, $alerttext, $staffignorelist = false, $departmentid = false, $fromname = false, $_alertdata = false)
	{
		global $_SWIFT, $template, $dbCore;

		if (!$staffignorelist)
		{
			$staffignorelist = array();
		}

		$alerttype = $this->alert["alerttype"];
//		echo "Processing Alert; $alerttype";
		$_stafflist = $this->getStaffList($departmentid);
		if (!count($_stafflist))
		{
			return false;
		}

		// See if tgroupid is set?
		$template->setGroup(iif(empty($this->ticket["tgroupid"]), 1, $this->ticket["tgroupid"]));
		$this->ticketobj->loadTemplateVariables();
		$template->loadLanguageSection("ticketemails", TEMPLATE_DB);
//		$template->assign("ticket", $this->ticket);
		$template->assign("alerttype", "email");
		if ($templatename == "alert_addnote" && _is_array($_alertdata))
		{
			$template->assign("notetype", $_alertdata["notetype"]);
		}
		$template->assign("ishtml", true);
		$_templateresulthtml = $template->displayTemplate($templatename, TEMPLATE_DB);
		$template->assign("ishtml", false);
		$_templateresulttext = $template->displayTemplate($templatename, TEMPLATE_DB);

//		print_r($_templateresulttext);

		if ($alerttype == ALERT_EMAIL)
		{
			require_once ("./includes/functions_mail.php");
			$mailObj = new SWIFT_Mail();

			if (!empty($this->ticketobj->messageid))
			{
				$messageid = sprintf('<staff.%s@%s>', $this->ticketobj->messageid, $mailObj->getLocalHost());
				$mailObj->setHeader("Message-ID", $messageid); // Set the Message-ID for this ticket
			}

			$mailObj->setSubject($this->ticketobj->getEmailSubject(SUBJECT_ALERT, "", $alerttext));
			$mailObj->setData($_templateresulthtml, $_templateresulttext);

			if (count($this->attachments))
			{
				foreach ($this->attachments as $key=>$val)
				{
					$mailObj->addAttachment(iif(!empty($val["data"]), $val["data"], $val["contents"]), $val["filename"], iif(!empty($val["contenttype"]), $val["contenttype"], 'application/octet-stream'));
				}
			}

			// Attachments for alerts, only for web submissions tho!
			if ($templatename == "alert_newticket" || $templatename == "alert_newreply")
			{
				if (_is_array($_FILES["opt_file"]["name"]))
				{
					$fileindex = 0;
					$_filelist = array();
					foreach ($_FILES["opt_file"]["name"] as $key=>$val)
					{
						if (!empty($val))
						{
							$_filelist[$fileindex]["name"] = $val;
							$_filelist[$fileindex]["type"] = $_FILES["opt_file"]["type"][$key];
							$_filelist[$fileindex]["tmp_name"] = $_FILES["opt_file"]["tmp_name"][$key];
							$_filelist[$fileindex]["error"] = $_FILES["opt_file"]["error"][$key];
							$_filelist[$fileindex]["size"] = $_FILES["opt_file"]["size"][$key];
							$fileindex++;
						}
					}

					// We have a file to add!
					if (count($_filelist))
					{
						foreach ($_filelist as $key=>$val)
						{
							if (file_exists($val["tmp_name"]))
							{
								$mailObj->addAttachment(implode("", file($val["tmp_name"])), $val["name"], iif(!empty($val["type"]), $val["type"], 'application/octet-stream'));
							}
						}
					}
					unset($_filelist);
				}
			}

			$emaillist = array();
			foreach ($_stafflist as $key=>$val)
			{
				if (!in_array($val["email"], $emaillist) && ($this->alert["execassign"] == 0 || ($this->alert["execassign"] == 1 && $this->ticket["ownerstaffid"] == $val["staffid"])) && !in_array($val["staffid"], $staffignorelist) && ($this->alert["alertscope"] == 1 || ($this->alert["alertscope"] == 0 && $this->alert["staffid"] == $val["staffid"])) && empty($_SWIFT["queuecache"]["p"][$val["email"]]))
				{
					$emaillist[] = $val["email"];
				}
			}
			if (count($emaillist))
			{
				$returnemail = $this->ticketobj->getReturnEmail();
				$returnname = iif($fromname, $fromname, $this->ticketobj->getReturnName());
				$mailObj->sendMail($emaillist, $returnemail, $returnname, false);
			}
		}
		
		if ($alerttype == ALERT_SMS) {
			$template->assign("alerttype", "sms");
			$_templateresult = $template->displayTemplate($templatename, TEMPLATE_DB);
			if (empty($_templateresult))
			{
				continue;
			}

			require_once ("./includes/functions_smsgateway.php");

			foreach ($_stafflist as $key=>$val)
			{
				if (!empty($val["mobilenumber"]) && ($this->alert["execassign"] == 0 || ($this->alert["execassign"] == 1 && $this->ticket["ownerstaffid"] == $val["staffid"])) && !in_array($val["staffid"], $staffignorelist) && ($this->alert["alertscope"] == 1 || ($this->alert["alertscope"] == 0 && $this->alert["staffid"] == $val["staffid"]))) {
					sendSMSAlert($this->ticketobj, $val["mobilenumber"], $_templateresult);
				}
			}
		}

		return false;
	}

	/**
	* Triggered when a ticket is flagged
	*/
	function doTicketFlagAlert($_alert, $_alertdata)
	{
		global $_SWIFT, $template;

		$this->processAlert("alert_flag", $_SWIFT["language"]["alert_flag"], array($_SWIFT["staff"]["staffid"]), false, iif(isset($_SWIFT["staff"]), $_SWIFT["staff"]["fullname"], false));
	}

	/**
	* Triggered on a new ticket. $contentstext and $contentshtml assigned by initiating function
	*/
	function doNewTicketAlert($_alert, $_alertdata)
	{
		global $_SWIFT;

		$ignorelist = array();
		if (!empty($_SWIFT["staff"]["staffid"]))
		{
			$ignorelist[] = $_SWIFT["staff"]["staffid"];
		}

		$this->processAlert("alert_newticket", $_SWIFT["language"]["alert_newticket"], $ignorelist, false, $_alertdata["fullname"]);
	}

	/**
	* Triggered on new reply, contents automatically assigned by calling function
	*/
	function doNewReplyAlert($_alert, $_alertdata, $isstaff = false)
	{
		global $_SWIFT, $template;

		$ignorelist = array();
		if (!empty($_SWIFT["staff"]["staffid"]))
		{
			$ignorelist[] = $_SWIFT["staff"]["staffid"];
		}
		if (!empty($_SWIFT["ruleignorestaffid"])) {
			$ignorelist[] = $_SWIFT["ruleignorestaffid"];
		}

		if ($isstaff)
		{
			$template->assign("replytype", "staff");
			$alerttext = $_SWIFT["language"]["alert_newstaffreply"];
		} else {
			$template->assign("replytype", "user");
			$alerttext = $_SWIFT["language"]["alert_newreply"];
		}
		

		$this->processAlert("alert_newreply", $alerttext, $ignorelist, false, $_alertdata["fullname"]);
	}

	/**
	* Executed on Ticket Move
	*/
	function doTicketMoveAlert($_alert, $_alertdata)
	{
		global $_SWIFT;

		$ignorelist = array();
		if (!empty($_SWIFT["staff"]["staffid"]))
		{
			$ignorelist[] = $_SWIFT["staff"]["staffid"];
		}

		$this->processAlert("alert_ticketmove", $_SWIFT["language"]["alert_move"], $ignorelist, $_alertdata["newdepartmentid"], iif(isset($_SWIFT["staff"]), $_SWIFT["staff"]["fullname"], false));
	}

	/**
	* Triggered when a new note is added to a ticket
	*/
	function doTicketNoteAlert($_alert, $_alertdata)
	{
		global $_SWIFT;

		$ignorelist = array();
		if (!empty($_SWIFT["staff"]["staffid"]))
		{
			$ignorelist[] = $_SWIFT["staff"]["staffid"];
		}
		// is for staff set? If yes, we will need to add every staff under this department to ignore list except for that one
		if (!empty($_alertdata["forstaffid"]))
		{
			$stafflist = $this->getStaffList();
			foreach ($stafflist as $key=>$val)
			{
				if ($val["staffid"] != $_alertdata["forstaffid"])
				{
					$ignorelist[] = $val["staffid"]; // Add to ignorelist
				}
			}
		}

		$this->processAlert("alert_addnote", $_SWIFT["language"]["alert_note"], $ignorelist, false, iif(isset($_SWIFT["staff"]), $_SWIFT["staff"]["fullname"], false), $_alertdata);
	}

	/**
	* Triggered on Ticket Status Change
	*/
	function doStatusChangeAlert($_alert, $_alertdata)
	{
		global $_SWIFT;

		$ignorelist = array();
		if (!empty($_SWIFT["staff"]["staffid"]))
		{
			$ignorelist[] = $_SWIFT["staff"]["staffid"];
		}

		$this->processAlert("alert_ticketstatus", $_SWIFT["language"]["alert_status"], $ignorelist, false, iif(isset($_SWIFT["staff"]), $_SWIFT["staff"]["fullname"], false));
	}
	
	/**
	* Executed on ticket priority change
	*/
	function doPriorityChangeAlert($_alert, $_alertdata)
	{
		global $_SWIFT;

		$ignorelist = array();
		if (!empty($_SWIFT["staff"]["staffid"]))
		{
			$ignorelist[] = $_SWIFT["staff"]["staffid"];
		}

		$this->processAlert("alert_ticketpriority", $_SWIFT["language"]["alert_priority"], $ignorelist, false, iif(isset($_SWIFT["staff"]), $_SWIFT["staff"]["fullname"], false));
	}

	/**
	* Triggered on ticket assignment
	*/
	function doTicketAssignAlert($_alert, $_alertdata)
	{
		global $_SWIFT;

		$ignorelist = array();
		if (!empty($_SWIFT["staff"]["staffid"]))
		{
			$ignorelist[] = $_SWIFT["staff"]["staffid"];
		}

		// Add all staff to ignore list except for the one to whom the ticket is assigned to
		$stafflist = $this->getStaffList();
		foreach ($stafflist as $key=>$val)
		{
			if ($val["staffid"] != $_alertdata["newownerstaffid"])
			{
				$ignorelist[] = $val["staffid"]; // Add to ignorelist
			}
		}

		$this->processAlert("alert_ticketassign", $_SWIFT["language"]["alert_assign"], $ignorelist, false, iif(isset($_SWIFT["staff"]), $_SWIFT["staff"]["fullname"], false));
	}

	/**
	* Triggered on Ticket Post Delete
	*/
	function doPostDeleteAlert($_alert, $_alertdata)
	{
		global $_SWIFT;

		$ignorelist = array();
		if (!empty($_SWIFT["staff"]["staffid"]))
		{
			$ignorelist[] = $_SWIFT["staff"]["staffid"];
		}

		$this->processAlert("alert_ticketpostdelete", $_SWIFT["language"]["alert_deletepost"], $ignorelist, false, iif(isset($_SWIFT["staff"]), $_SWIFT["staff"]["fullname"], false));
	}

	/**
	* 
	*/
	function doTicketDeleteAlert($_alert, $_alertdata)
	{
		
	}

	/**
	* 
	*/
	function doTicketMergeAlert($_alert, $_alertdata)
	{
		
	}

	/**
	* 
	*/
	function doTicketEditAlert($_alert, $_alertdata)
	{
		
	}
}
?>